package com.qunar.homework2.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.*;
@Slf4j
@Service
public class StatistiscService {
    List<Map.Entry<String, Integer>> Statistics(File dir) {
        File[] logFiles = dir.listFiles();
        Map<String, Integer> map = new HashMap<>();
        String tmp;
        for (File f : logFiles){
            if (f.isDirectory()) {
                Statistics(f);
            }
            if (!f.getName().equals("accesslog")) {
                continue;
            }
            try (FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr)){
                while ((tmp = br.readLine()) != null){
                    tmp = tmp.substring(0, tmp.indexOf(" "));
                    if (map.containsKey(tmp)){
                        map.put(tmp, map.get(tmp) + 1);
                    }else {
                        map.put(tmp, 1);
                    }
                }
            }catch (Exception e){
                System.out.print("io exception");
            }
        }
        PriorityQueue<Map.Entry<String, Integer>> queue = new PriorityQueue<>(10, Comparator.comparingInt(Map.Entry::getValue));
        for (Map.Entry<String, Integer> entry : map.entrySet()){
            queue.add(entry);
            if (queue.size() > 10){
                queue.poll();
            }
        }
        List<Map.Entry<String, Integer>> res = new ArrayList<>(queue);
        return res;
    }
}
